import { chromium, FullConfig } from '@playwright/test';
import * as dotenv from 'dotenv';
import path from 'path';

// 加载测试环境变量
dotenv.config({ path: path.join(__dirname, '.env.test') });

async function globalSetup(config: FullConfig) {
  console.log('🚀 开始全局设置...');

  // 启动浏览器进行初始化设置
  const browser = await chromium.launch({
    headless: true,
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });

  const context = await browser.newContext({
    viewport: { width: 1920, height: 1080 },
    ignoreHTTPSErrors: true,
  });

  const page = await context.newPage();

  try {
    // 等待应用启动
    console.log('⏳ 等待应用启动...');
    await page.goto(process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:3001', {
      waitUntil: 'networkidle',
      timeout: 30000
    });

    // 检查应用是否正常启动
    const title = await page.title();
    console.log(`📱 应用标题: ${title}`);

    // 验证页面是否加载完成
    await page.waitForLoadState('domcontentloaded', { timeout: 10000 });
    console.log('✅ 应用页面加载成功');

    // 检查API连接
    try {
      const apiResponse = await page.request.get(`${process.env.REACT_APP_API_URL}/api/agent-platform/performance/health`);
      if (apiResponse.ok()) {
        console.log('✅ API连接正常');
      } else {
        console.log('⚠️  API连接可能有问题，状态码:', apiResponse.status());
      }
    } catch (error) {
      console.log('⚠️  API连接检查失败:', error.message);
    }

  } catch (error) {
    console.error('❌ 全局设置失败:', error);
    throw error;
  } finally {
    await context.close();
    await browser.close();
  }

  console.log('✅ 全局设置完成');
}

export default globalSetup;